<template>
  <div class="default-main ba-table-box">
    <TableHeader
      :buttons="['refresh', 'columnDisplay']"
      @action="baTable.onTableHeaderAction"
    />
    <Table ref="tableRef" @action="baTable.onTableAction" />
    <!-- 表单 -->
    <Info />
  </div>
</template>
<script lang="ts" setup>
import { ref, inject, onMounted, provide, onBeforeUnmount } from "vue";
import baTableClass from "@/utils/baTable";
import _ from "lodash";
import { baTableApi, buildJsonToElTreeData } from "@/utils/common";
import Table from "@/components/table/index.vue";
import TableHeader from "@/components/table/header/index.vue";
import useCurrentInstance from "@/utils/useCurrentInstance";
import type { TableRow, TableColumn } from "@/utils/baTable"; //表格列行类型
import { LineCruiseItems } from "@/api/backend/index";
import { useStandard } from "@/store/backend/LineCruiseM/standard";
import { useStandardItems } from "@/store/backend/LineCruiseM/items";
import { useRoute } from "vue-router";
import Info from "./info.vue";

const { proxy } = useCurrentInstance(); //mitt
const tableRef = ref();
// const dict = useDictionary();
const standard = useStandard();
const items = useStandardItems();
const route = useRoute();
const navTabs = inject("navTabs") as any;

//字段显隐记忆功能
const filedShowOff = (filter: any) => {
  if ((navTabs as any).columnDisplayStoreMap) {
    return (navTabs as any).columnDisplayStoreMap.get(
      route.path + "/" + filter
    );
  }
  return true;
};
// 每页个数记忆功能
const pageSizeKeep = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + LineCruiseItems)
      ? (navTabs as any).pageSizeMap.get(route.path + LineCruiseItems)
      : 10;
  }
  return 10;
};
//历史记录页数记忆功能
const pageSizeKeepOfHistory = () => {
  if ((navTabs as any).pageSizeMap) {
    return (navTabs as any).pageSizeMap.get(route.path + LineCruiseItems)
      ? (navTabs as any).pageSizeMap.get(route.path + LineCruiseItems)
      : false;
  }
  return false;
};

const baTable = new baTableClass(
  new baTableApi(LineCruiseItems), //this.api = api菜单管理相关
  {
    pk: "id",
    column: [
      { type: "selection", align: "center", operator: false },
      {
        show: filedShowOff("name"),
        label: "检查项",
        prop: "name",
        align: "center",
        render: "customTemplate",
        customTemplate: (row: TableRow, field: TableColumn, value: any) => {
          let i = standard.equipmentInfos[
            standard.itemsIndex
          ].standardList.findIndex((val: any) => {
            return val.name === value;
          });
          if (i !== -1) {
            if (
              standard.equipmentInfos[standard.itemsIndex].standardList[i]
                .status === 0
            ) {
              //异常
              return "<p style='color:red;'>" + value + "</p>";
            }
            return "<p style='color:#409eff;'>" + value + "</p>";
          }
          return "";
        },
      },
      {
        label: "操作",
        align: "center",
        width: "130",
        operator: false,
        render: "buttons",
        fixed: "right",
        buttons: [
          {
            render: "tipButton",
            name: "editItems",
            title: "详情",
            text: "",
            type: "primary",
            icon: "iconfont icon-tianchong",
            class: "table-row-edit",
            disabledTip: false,
            // 按钮是否显示，请返回布尔值
            display: (row: TableRow, field: TableColumn) => {
              return true;
            },
            // 按钮是否禁用，请返回布尔值
            disabled: (row: TableRow, field: TableColumn) => {
              return false;
            },
            attr: {},
          },
        ],
      },
    ],
    filter: {
      pageSize: pageSizeKeep(),
    },
  },
  {},
  {
    onTableDblclick: ({ row }: { row: TableRow }) => {
      infoButtonClickItems(row);
      return false;
    },
    getList: () => {
      baTable.api
        .list("", { groupIds: standard.groupIds, pageSize: pageSizeKeep() })
        .then((res: any) => {
          console.log("标准项", res);

          baTable.table.data = res.rows;
          baTable.table.total = res.total;
        })
        .catch((err) => {});
      return false;
    },
  }
);
//pinia对state的订阅监听使用$subscribe
standard.$subscribe((state) => {
  baTable.getList("");
});
//修改字典项
const emit = defineEmits(["onPut"]);
// const editStandard = (name: string, row: any) => {
//   //将详情赋值给添加表单
//   emit("onPut", row);
// };
//
const removeStandard = (name: string, row: anyObj) => {
  items
    .deleteStandardSet(row)
    .then((res) => {
      baTable.getList("");
    })
    .catch((err) => {
      baTable.getList("");
    });
};
/**
 * 表格内的按钮响应
 * @param name 按钮name
 * @param row 被操作行数据
 */
proxy.eventBus.on("onTableButtonClick", (data: { name: string; row: any }) => {
  console.log("data", data);
  if (data.name == "editItems") {
    //编辑
    // editStandard(data.name, data.row);
    infoButtonClickItems(data.row);
    // standard.opera = "edit";
  } else if (data.name == "removeItems") {
    //删除
    removeStandard(data.name, data.row);
  }
});

/** 点击查看详情按钮响应 */
const infoButtonClickItems = (row: TableRow) => {
  if (!row) return;
  let i = standard.equipmentInfos[standard.itemsIndex].standardList.findIndex(
    (val: any) => {
      return val.name === row.name;
    }
  );
  // 数据来自表格数据,未重新请求api,深克隆,不然可能会影响表格
  let rowClone = _.cloneDeep(
    standard.equipmentInfos[standard.itemsIndex].standardList[i]
  );
  rowClone.operParam = rowClone.operParam
    ? [
        {
          label: "点击展开",
          children: buildJsonToElTreeData(JSON.parse(rowClone.operParam)),
        },
      ]
    : [];

  baTable.form.extend!["info"] = rowClone;
  console.log("baTable.form.extend", baTable.form.extend!["info"]);

  baTable.form.operate = "info";
};

onMounted(() => {
  //将table的ref给到table类
  baTable.table.ref = tableRef.value;
  baTable.mount();
  baTable.getList(LineCruiseItems);
  /**
   * 表格内的按钮响应
   * @param name 按钮name
   * @param row 被操作行数据
   */
  // proxy.eventBus.on(
  //   "onTableButtonClick",
  //   (data: { name: string; row: TableRow }) => {
  //     if (!baTable.activate) return;
  //     if (data.name == "info") {
  //       infoButtonClickItems(data.row);
  //     }
  //   }
  // );
});
// 实例化表格后，将 baTable 的实例提供给上下文
provide("baTable", baTable);

proxy.eventBus.on("refreshStandard", () => {
  baTable.getList("");
});

proxy.eventBus.on("pagesize", (res: any) => {
  console.log("pagesize", route.query);
  baTable.table.loading = true;
  items.pageSize = pageSizeKeepOfHistory()
    ? pageSizeKeepOfHistory()
    : res.pageSize;
  items.getStandardItemsListTask().then((res: any) => {
    baTable.table.data = res.rows;
    baTable.table.total = res.total;
    baTable.table.loading = false;
  });
});
proxy.eventBus.on("pageNum", (res: any) => {
  console.log("pageNum", route.query);
  baTable.table.loading = true;
  items.pageNum = res.pageNum;
  items.getStandardItemsListTask().then((res: any) => {
    baTable.table.data = res.rows;
    baTable.table.total = res.total;
    baTable.table.loading = false;
  });
});

onBeforeUnmount(() => {
  items.pageNum = 1;
  items.pageSize = pageSizeKeep();
  proxy.eventBus.off("pageNum");
  proxy.eventBus.off("pagesize");
});
</script>
<style lang="scss" scoped>
.ba-operate-dialog {
  .ba-operate-form {
    .formTip {
      margin-left: 120px;
    }

    .el-form {
      :deep(.el-form-item__content) {
        margin-top: 10px;
      }
    }
  }
}

@media screen and (max-width: 460px) {
  .ba-operate-dialog {
    .ba-operate-form {
      .formTip {
        margin-left: 0px;
      }

      .el-form {
        :deep(.el-form-item__content) {
          margin: 10px 0 0 0;
        }
      }
    }
  }
}
</style>
